package com.example.rabbitmq.config;


import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DeadLetterConfig {
    // 普通交换机
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    // 普通队列
    public static final String NORMAL_QUEUE = "normal_queue";

    // 死信交换机
    public static final String DEAD_EXCHANGE = "dead_exchange";
    // 死信队列
    public static final String DEAD_QUEUE = "dead_queue";

    // 路由键
    public static final String NORMAL_ROUTING_KEY = "normal.key";
    public static final String DEAD_ROUTING_KEY = "dead.key";

    // 声明死信交换机
    @Bean
    public Exchange deadExchange() {
        return ExchangeBuilder.directExchange(DEAD_EXCHANGE).durable(true).build();
    }

    // 声明死信队列
    @Bean
    public Queue deadQueue() {
        return QueueBuilder.durable(DEAD_QUEUE).build();
    }

    // 声明普通交换机
    @Bean
    public Exchange normalExchange() {
        return ExchangeBuilder.directExchange(NORMAL_EXCHANGE).durable(true).build();
    }

    // 声明普通队列并绑定死信交换机
    @Bean
    public Queue normalQueue() {
        Map<String, Object> args = new HashMap<>();
        // 设置死信交换机
        args.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        // 设置死信路由键
        args.put("x-dead-letter-routing-key", DEAD_ROUTING_KEY);
        // 设置队列消息过期时间（10秒）
        args.put("x-message-ttl", 10000);
        // 设置队列最大长度
        args.put("x-max-length", 10);

        return QueueBuilder.durable(NORMAL_QUEUE).withArguments(args).build();
    }

    // 绑定普通队列和普通交换机
    @Bean
    public Binding normalBinding() {
        return BindingBuilder.bind(normalQueue()).to(normalExchange()).with(NORMAL_ROUTING_KEY).noargs();
    }

    // 绑定死信队列和死信交换机
    @Bean
    public Binding deadBinding() {
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with(DEAD_ROUTING_KEY).noargs();
    }
}
